package cn.zwz.bill.controller;

import cn.zwz.basics.baseVo.PageVo;
import cn.zwz.basics.baseVo.Result;
import cn.zwz.basics.utils.PageUtil;
import cn.zwz.basics.utils.ResultUtil;
import cn.zwz.basics.utils.SecurityUtil;
import cn.zwz.bill.entity.Bill;
import cn.zwz.bill.entity.Commodity;
import cn.zwz.bill.entity.Stock;
import cn.zwz.bill.entity.Supplier;
import cn.zwz.bill.service.IBillService;
import cn.zwz.bill.service.ICommodityService;
import cn.zwz.bill.service.IStockService;
import cn.zwz.bill.service.ISupplierService;
import cn.zwz.bill.utils.DateUtils;
import cn.zwz.data.entity.User;
import cn.zwz.data.service.IUserService;
import cn.zwz.data.utils.ZwzNullUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@Api(tags = "库存管理")
@RequestMapping("/zwz/stock")
@Transactional
public class StockController {

    @Autowired
    private IStockService iStockService;

    @Autowired
    private IBillService iBillService;

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private ICommodityService iCommodityService;

    @Autowired
    private ISupplierService iSupplierService;

    @Autowired
    private IUserService iUserService;

    @RequestMapping(value = "/get", method = RequestMethod.GET)
    @ApiOperation(value = "查询单个库存")
    public Result<Stock> get(@RequestParam String id){
        Stock stock = iStockService.getById(id);
        return new ResultUtil<Stock>().setData(stock);
    }

    @RequestMapping(value = "/getByBarCode/{barCode}", method = RequestMethod.GET)
    @ApiOperation(value = "查询单个商品")
    public Result<Commodity> getCommodityBaBarCode(@PathVariable String barCode){
        QueryWrapper<Commodity> commodityQueryWrapper = new QueryWrapper<>();
        commodityQueryWrapper.eq("bar_code", barCode);
        commodityQueryWrapper.eq("state","上架");
        Commodity commodity = iCommodityService.getOne(commodityQueryWrapper);
        return new ResultUtil<Commodity>().setData(commodity);
    }

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @ApiOperation(value = "查询全部库存")
    public Result<List<Stock>> getAll(){
        List<Stock> list = iStockService.list();
        return new ResultUtil<List<Stock>>().setData(list);
    }

    @RequestMapping(value = "/getByPage", method = RequestMethod.GET)
    @ApiOperation(value = "查询库存")
    public Result<IPage<Stock>> getByPage(@ModelAttribute Stock stock, @ModelAttribute PageVo page){
        QueryWrapper<Stock> qw = new QueryWrapper<>();
        if(!ZwzNullUtils.isNull(stock.getState())) {
            qw.eq("state",stock.getState());
        }
        System.out.println("11111111111111111111111111111111111111");
        System.out.println(stock.getDateTime());
        System.out.println("11111111111111111111111111111111111111");
        IPage<Stock> data = iStockService.page(PageUtil.initMpPage(page),qw);
        for (Stock stock1 : data.getRecords()) {
            Supplier supplier = iSupplierService.getById(stock1.getSupplierId());
            if(supplier != null) {
                stock1.setSupplierName(supplier.getName());
            } else {
                stock1.setSupplierName("无");
            }
            User user = iUserService.getById(stock1.getUserId());
            if(user != null) {
                stock1.setUserName(user.getNickname());
            } else {
                stock1.setUserName("无");
            }
        }
        return new ResultUtil<IPage<Stock>>().setData(data);
    }

    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    @ApiOperation(value = "新增入库存")
    public Result<Stock> insertIn(@RequestBody Stock stock) {
        stock.setDateTime(DateUtils.getCompleteNowDate());
        stock.setUserId(securityUtil.getCurrUser().getId());
//        stock.setState("0");
//        String price = stock.getPrice();
//        String number = stock.getNumber();
//        Double sum = Double.parseDouble(price) * Double.parseDouble(number);
//        sum = Math.ceil(sum * 10.0) / 10.0;
//        stock.setSum(sum + "");
        if(iStockService.saveOrUpdate(stock)){
            //根据订购的商品，生成账单信息，
            List<Commodity> commodityList = stock.getCommodityList();
            for (Commodity c : commodityList) {
                Bill bill = new Bill();
                bill.setCommodityId(c.getId());
                bill.setSupplierId(c.getSupplierId());
                bill.setUserId(stock.getUserId());
                bill.setDateTime(stock.getDateTime());
                double number = Double.parseDouble(c.getBuyNumber()) + Double.parseDouble(c.getGiveNumber());
                bill.setNumber(number + "");
                double num = Double.parseDouble(c.getBuyNumber()) * Double.parseDouble(c.getPrice());
                bill.setPrice(c.getPrice() + "");
                bill.setSum(num + "");
                bill.setStockId(stock.getId());
                bill.setState(stock.getState());
                iBillService.saveOrUpdate(bill);
                double commodityNumber = Double.parseDouble(c.getBuyNumber()) + Double.parseDouble(c.getGiveNumber()) + Double.parseDouble(c.getStock());
                c.setStock(commodityNumber + "");
                c.setParentId(stock.getId());
                iCommodityService.saveOrUpdate(c);
            }
            return new ResultUtil<Stock>().setData(stock);
        }
        return new ResultUtil<Stock>().setErrorMsg("新增库存失败");
    }
    @RequestMapping(value = "/insertout", method = RequestMethod.POST)
    @ApiOperation(value = "新增出库存")
    public Result<Stock> insertOut(@RequestBody Stock stock) {
        stock.setDateTime(DateUtils.getCompleteNowDate());
        stock.setUserId(securityUtil.getCurrUser().getId());

        List<Commodity> commodityList = stock.getCommodityList();
        for (Commodity c :commodityList) {
            double commodityNumber = Double.parseDouble(c.getStock()) - Double.parseDouble(c.getBuyNumber());
            if (commodityNumber < 0){
                return new ResultUtil<Stock>().setErrorMsg("库存不够！");
            }
        }

        if(iStockService.saveOrUpdate(stock)){
            //根据订购的商品，生成账单信息，
            for (Commodity c : commodityList) {
                Bill bill = new Bill();
                bill.setCommodityId(c.getId());
                bill.setSupplierId(c.getSupplierId());
                bill.setUserId(stock.getUserId());
                bill.setDateTime(stock.getDateTime());
                bill.setParentId(c.getParentId());
                double number = Double.parseDouble(c.getBuyNumber());
                bill.setNumber(number + "");
                bill.setPrice(c.getUnitPrice() + "");
                double num = Double.parseDouble(c.getBuyNumber()) * Double.parseDouble(c.getUnitPrice());
                bill.setSum(String.format("%.2f",num));
                bill.setStockId(stock.getId());
                bill.setState(stock.getState());
                double commodityNumber = Double.parseDouble(c.getStock()) - Double.parseDouble(c.getBuyNumber());
                iBillService.saveOrUpdate(bill);
                c.setStock(commodityNumber + "");
                iCommodityService.saveOrUpdate(c);
            }
            return new ResultUtil<Stock>().setData(stock);
        }
        return new ResultUtil<Stock>().setErrorMsg("新增出库存失败");
    }

//不需要修改删除
//    @RequestMapping(value = "/update", method = RequestMethod.POST)
//    @ApiOperation(value = "编辑账单")
//    public Result<Stock> update(Stock stock) {
//        if(iStockService.saveOrUpdate(stock)){
//            return new ResultUtil<Stock>().setData(stock);
//        }
//        return new ResultUtil<Stock>().setErrorMsg("编辑账单失败");
//    }
//    @RequestMapping(value = "/delByIds", method = RequestMethod.POST)
//    @ApiOperation(value = "删除账单")
//    public Result<Object> delAllByIds(@RequestParam String[] ids) {
//        for(String id : ids){
//            iStockService.removeById(id);
//        }
//        return ResultUtil.success();
//    }


}
